package com.yanxibao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanxibao.bean.Comments;
import com.yanxibao.common.Result;
import com.yanxibao.dto.CommentsUserDTO;
import com.yanxibao.dto.UserDTO;
import com.yanxibao.service.CommentsService;
import com.yanxibao.mapper.CommentsMapper;
import com.yanxibao.util.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import static com.yanxibao.util.RedisConstants.COMMENTS_LIKE_KEY;


/**
 * 评论服务实现
 *
 * @description 针对表【yxb_comments(评论表)】的数据库操作Service实现
 * @createDate 2023-11-19 20:12:45
 * @date 2023/11/23
 */
@Service
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments> implements CommentsService{

    @Resource
    private CommentsMapper commentsMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 增添评论
     * @param comments 评论
     * @return
     */
    @Override
    public Result<Comments> addComments(Comments comments) {
        int insert = commentsMapper.insert(comments);
        return insert==1 ? Result.success():Result.error("08000","添加失败！");
    }

    /**
     * 查询评论信息及用户信息
     * @return
     */
    @Override
    public Result<List<CommentsUserDTO>> getCommentsList(Integer blogId) {
        List<CommentsUserDTO> commentsUserDTOSList = commentsMapper.selectCommentsUser(blogId);
        if(commentsUserDTOSList.isEmpty()){
            return Result.error("08010","未查询到评论信息！");
        }
        commentsUserDTOSList.forEach(this::isCommentsLikes);
        return Result.success(commentsUserDTOSList);
    }

    /**
     * 判断评论是否被点赞过
     * @param commentsUserDTO 评论用户信息
     */
    private void isCommentsLikes(CommentsUserDTO commentsUserDTO){
        UserDTO userDTO = UserHolder.getUser();
        if(userDTO == null){
            return;
        }
        String userId = userDTO.getUserId();
        String key = COMMENTS_LIKE_KEY + commentsUserDTO.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        commentsUserDTO.setIsLikes(score != null);
    }

    /**
     * 删除评论信息
     * @param id
     * @return
     */
    @Override
    public Result<Boolean> deleteComments(Integer id) {
        UserDTO userDTO = UserHolder.getUser();
        Comments comments = commentsMapper.selectById(id);
        if(comments == null){
            return Result.error("08030","评论不存在！");
        }
        if(!comments.getUserId().equals(userDTO.getUserId())){
            return Result.error("08031","该评论不是您的，您无权限删除！");
        }
        int i = commentsMapper.deleteById(id);
        return i==1 ? Result.success():Result.error("08032","删除失败！");
    }

    /**
     * 用户点赞功能
     * @param id
     * @return
     */
    @Override
    public Result<Integer> likes(Integer id) {
        //1.获取登录用户
        String userId = UserHolder.getUser().getUserId();
        //2.判断当前用户是否被点赞
        String key = COMMENTS_LIKE_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        if(score == null){
            //3.如果未点赞，可点赞
            //3.1.数据点赞数 + 1
            boolean isSuccess = update().setSql("likes = likes + 1").eq("id",id).update();
            //3.2.保存用户到Redis的set集合中
            if(isSuccess){
                // 把时间戳作为分数保存到redis的set集合中 zadd key value score
                stringRedisTemplate.opsForZSet().add(key,userId,System.currentTimeMillis());
            }
        }else {
            //如果已经点赞
            //数据库中点赞数减一
            boolean success = update().setSql("likes = likes - 1").eq("id", id).update();
            if(success){
                // 把点赞记录从redis中去除
                stringRedisTemplate.opsForZSet().remove(key,userId);
            }
        }
        return Result.success();
    }


}




